package com.edu.controller;

import com.edu.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/session")
public class SessionSafety {
    /**
     *   SpringMVC中的Controller 默认是单例模式
     *      Spring容器当中 只会有一个 SessionSafety这个对象
     */
    @RequestMapping("/session1")
    public String session1(User user, HttpSession session){
        System.out.println(user);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(user);
        session.setAttribute("loginUser",user);

        return "forward:/success.jsp";
    }

//    private String testName;
//
//    @RequestMapping("/test")
//    public String test(String testName, HttpServletRequest request){
//        this.testName = testName;
//        System.out.println(this.testName);
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(this.testName);
//        request.setAttribute("testName",this.testName);
//        return "forward:/success2.jsp";
//    }
//    @Resource
//    private HttpSession session;
//
//    @RequestMapping("/session2")
//    public String session2(User user){
//        System.out.println(user);
//        System.out.println(session);
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(session);
//        session.setAttribute("loginUser",user);
//        return "forward:/success.jsp";
//    }


    private HttpSession session;

    @ModelAttribute
    public void init(HttpSession session){
        this.session = session;
    }


    @RequestMapping("/session3")
    public String session3(User user){
        System.out.println(user);
        System.out.println(session+"-"+user);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(session+"-"+user);
        session.setAttribute("loginUser",user);
        return "forward:/success.jsp";
    }

}
